/*
Copyright 2008  Four Roads LLC conact@4-roads.com

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either 
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with this library.  If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Web;
using System.Web.UI;


namespace FourRoads.Links
{
	/// <summary>
	/// Summary description for ScrollPosMgr.
	/// </summary>
	public class ScrollPosMgr
	{
		private const string _scrollScript = "<script>scrollTo({0},{1});</script>";
		private const string _scrollScriptReg = "DoScrollFunc";
		private const string _scrollPosScriptReg = "TrackScrollPos";
		private const string _inputId = "FourRoadsScrollPos";
		private const string _onscrollScript = 
			"<script language='javascript'>onscroll = function(){{document.getElementById('{0}').value " + 
			" = document.body.scrollLeft+'#' + document.body.scrollTop;}}</script>";

		public void Page_LoadScrollPosTrack(object sender, EventArgs e)
		{
			//THis is called need to add in out script blocks and if its a post back retrieve the 
			//old data and create a script block at the bottom to monitor the scroll positions
			if (sender is Page)
			{   //Thats a good start
				Page pg = sender as Page;

				//this.ID = _inputId;
				pg.RegisterHiddenField(_inputId , "");

				//add the tracking functionlaity
				if (!pg.IsClientScriptBlockRegistered(_scrollPosScriptReg))
				{
					//Fill in the missing parameter
					string script = string.Format(_onscrollScript , _inputId );

					pg.RegisterClientScriptBlock(_scrollPosScriptReg , script);
				}

				if (pg.IsPostBack)
				{
					//Add the function to restore the position
					if (pg.Request.Params[_inputId] != null)
					{
						if (pg.Request.Params[_inputId].Length > 0)
						{
							if (!pg.IsStartupScriptRegistered(_scrollScriptReg))
							{
								string unformatedData = pg.Request.Params[_inputId];
								string[] vals = unformatedData.Split( Char.Parse("#") );

								string script = string.Format(_scrollScript , vals[0]  , vals[1] );

								pg.RegisterStartupScript(_scrollScriptReg , script);
							}
						}
					}
				}
			}
		}
	}
}
